﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace Alibobo.Util
{
    public class SettingBase
    {
        [XmlIgnore]
        protected string m_fileName;

        public string FileName
        {
            get { return m_fileName; }
            set { m_fileName = value; }
        }


        public virtual void Save(string fileName)
        {
            XmlSerializer ser = null;

            try
            {
                ser = new XmlSerializer(this.GetType());
                using (TextWriter tw = new StreamWriter(fileName))
                {
                    ser.Serialize(tw, this);
                }
            }
            catch (Exception ex)
            {
                throw new System.Exception(String.Format("Saving settings class '{0}' to {1} failed", this.GetType().ToString(), fileName), ex);
            }
        }

        public static SettingBase Load(string fileName,SettingBase defaultSettings)
        {

            // remember where we loaded from for a later save
            defaultSettings.m_fileName = fileName;
            // return the default instance if the file does not exist
            if (!File.Exists(fileName))
            {
                return defaultSettings;
            }

            // start out with the default instance
            SettingBase settings = defaultSettings;
            try
            {
                XmlSerializer ser = new XmlSerializer(defaultSettings.GetType());
                using (TextReader tr = new StreamReader(fileName))
                {
                    settings = (SettingBase)ser.Deserialize(tr);
                    settings.m_fileName = fileName; // remember where we loaded from for a later save
                }
            }
            catch (Exception ex)
            {
                throw new System.Exception(String.Format("Loading settings from file '{1}' to {0} failed",
                    defaultSettings.GetType().ToString(), fileName), ex);
            }

            return settings;
        }

    }
}
